const API=(function(){
    const BASE_URL='https://study.duyiedu.com';
const THE_KEY='token';
function get(path){
    const headers={};
    const token=localStorage.getItem(THE_KEY);
    if(token){//--------------判断是否有令牌，有就将令牌也发给服务器
        headers.authorization=`Bearer+${token}`;
    }
    return fetch(BASE_URL+path,{headers});
}
function post(path,bodyobj){
    const headers={
        'content-type':'application/json',
    };
    const token=localStorage.getItem(THE_KEY);
    if(token){
        headers.authorization=`Bearer+${token}`;
    }
    return fetch(BASE_URL+path,{headers,method:'POST',body:JSON.stringify(bodyobj)});
}
async function reg (userInfo){//注册
   const resp=await post('/api/user/reg',userInfo);
    return await resp.json();
}
async function login(loginInfo){//登录
    const resp=await post('/api/user/login',loginInfo);
    const result=await resp.json();
    const token=resp.headers.get('authorization');
    if(result.code===0)
    {
        localStorage.setItem(THE_KEY,token);//保存令牌
    }
        return await result;
}
async function exists (loginId){
    const result=await get('/api/user/exists?loginId='+loginId);
    return await result.json();
}//验证账号
async function profile(){//当前登录的用户信息 
   const result=await get('/api/user/profile');
   return await result.json();
}      
async function sendChart(content){//发送消息
    const result=await post('/api/chat',{content});
    return result.json();
}
async function getHistory(){ //得到历史消息
    const result=await get('/api/chat/history');
    return await result.json();
}
function loginout(){
    localStorage.removeItem(THE_KEY);
}


return{
    reg,
    login,
    exists,
    profile,
    sendChart,
    getHistory,
    loginout
}
})()